<template>
  <div>
    <vxe-toolbar style="margin-bottom: 10px">
      <template #buttons>
        <vxe-button
          status="primary"
          icon="vxe-icon-square-plus"
          @click="insertEvent"
          >新增</vxe-button
        >
        <vxe-button
          status="primary"
          icon="vxe-icon-download"
          @click="exportData"
          >导出所有数据</vxe-button
        >
        <vxe-button
          status="primary"
          icon="vxe-icon-download"
          @click="generateReport"
          >导出PDF</vxe-button
        >
        <vxe-button
          status="primary"
          icon="vxe-icon-download"
          @click="exportDataEvent"
          >导出其他格式文件</vxe-button
        >
      </template>
    </vxe-toolbar>
    <vxe-table
      :export-config="{}"
      v-if="tableData"
      :loading="loading"
      ref="xTable"
      height="530"
      max-height="530"
      show-overflow
      border="full"
      align="center"
      :row-config="{ isHover: true, height: 100 }"
      :column-config="{ resizable: true }"
      :data="tableData"
    >
      <vxe-column type="seq" title="序号" width="60"></vxe-column>
      <vxe-column field="category" title="新闻类型" width="80"></vxe-column>
      <vxe-column field="author" title="新闻作者" width="80"></vxe-column>
      <vxe-column field="title" title="新闻标题"></vxe-column>
      <vxe-column title="新闻图片" width="200">
        <template #default="{ row }">
          <img
            v-lazyImg="row.image"
            :data-src="row.image"
            class="image"
            style="width: 100px; height: 100px"
            alt="Example Image"
          />
        </template>
      </vxe-column>
      <vxe-column title="操作" width="200">
        <template #default="{ row }">
          <vxe-button
            status="primary"
            icon="vxe-icon-info-circle-fill"
            @click="Details(row)"
          ></vxe-button>
          <vxe-button
            status="primary"
            icon="vxe-icon-edit"
            @click="recompose(row)"
          ></vxe-button>
          <el-popconfirm
            :title="`确认删除${row.title}吗？`"
            @confirm="deleteNewsList(row.id)"
          >
            <template #reference>
              <vxe-button status="danger" icon="vxe-icon-delete"></vxe-button>
            </template>
          </el-popconfirm>
        </template>
      </vxe-column>
    </vxe-table>
    <el-pagination
      style="margin-top: 20px"
      v-model:current-page="page"
      v-model:page-size="limit"
      :page-sizes="[20, 40, 60]"
      :small="false"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="(val: number) => getNewsList(1,val)"
      @current-change="(val: number) => getNewsList(val,limit)"
    />
    <vxe-modal
      v-model="showEdit"
      min-width="600"
      width="1000"
      :show-footer="false"
      height="600"
      :draggable="false"
      @hide="EmptyForm"
    >
      <template #title>
        <span v-if="!AddNus" style="color: red"> 新闻详情 </span>
        <span v-else style="color: red">{{
          !formData.id ? "添加数据" : "修改数据"
        }}</span>
      </template>
      <div v-if="!AddNus">
        <el-row style="margin: 5px 0">
          <el-col :span="3"
            ><div class="grid-content ep-bg-purple">新闻类型：</div></el-col
          >
          <el-col :span="21"
            ><div class="grid-content ep-bg-purple-light">
              {{ formData.category }}
            </div>
          </el-col>
        </el-row>
        <el-row style="margin: 5px 0">
          <el-col :span="3"
            ><div class="grid-content ep-bg-purple">新闻标题：</div></el-col
          >
          <el-col :span="21"
            ><div class="grid-content ep-bg-purple-light">
              {{ formData.title }}
            </div>
          </el-col>
        </el-row>
        <el-row style="margin: 5px 0">
          <el-col :span="3"
            ><div class="grid-content ep-bg-purple">新闻作者：</div></el-col
          >
          <el-col :span="21"
            ><div class="grid-content ep-bg-purple-light">
              {{ formData.author }}
            </div>
          </el-col>
        </el-row>
        <el-row style="margin: 5px 0">
          <el-col :span="3"
            ><div class="grid-content ep-bg-purple">新闻图片：</div></el-col
          >
          <el-col :span="21"
            ><div class="grid-content ep-bg-purple-light">
              <el-image
                style="width: 150px; height: 100px"
                :src="formData.image"
                fit="fill"
                lazy
                alt="Example Image"
              />
            </div>
          </el-col>
        </el-row>
        <el-row style="margin: 5px 0">
          <el-col :span="3"
            ><div class="grid-content ep-bg-purple">新闻详情：</div></el-col
          >
          <el-col :span="21"
            ><div
              class="grid-content ep-bg-purple-light"
              v-html="formData.content"
            ></div>
          </el-col>
        </el-row>
        <el-row style="margin: 5px 0">
          <el-col :span="20"></el-col>
          <el-col :span="4">
            <vxe-button
              status="primary"
              content="修改"
              @click="AddNus = true"
            ></vxe-button>
            <vxe-button
              status="primary"
              content="关闭"
              @click="showEdit = false"
            ></vxe-button>
          </el-col>
        </el-row>
      </div>
      <div v-else>
        <el-form
          class="demo-ruleForm"
          :rules="rules"
          :model="formData"
          ref="ruleFormRef"
        >
          <el-form-item label="新闻类型" prop="category">
            <el-input v-model="formData.category" />
          </el-form-item>
          <el-form-item label="新闻标题" prop="title">
            <el-input v-model="formData.title" />
          </el-form-item>
          <el-form-item label="新闻作者" prop="author">
            <el-input v-model="formData.author" />
          </el-form-item>
          <el-form-item label="新闻图片" prop="image">
            <el-upload
              class="avatar-uploader"
              :action="`${BASE_URL}/admin/product/upload`"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <el-icon v-if="uploadLoading" class="avatar-uploader-icon"
                ><Loading
              /></el-icon>
              <img
                alt="Example Image"
                v-else-if="formData.image"
                :src="formData.image"
                class="avatar"
              />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="新闻详情" prop="content">
            <quill-editor
              theme="snow"
              toolbar="full"
              contentType="html"
              v-model:content="formData.content"
            ></quill-editor>
          </el-form-item>
        </el-form>
        <el-row style="margin: 5px 0">
          <el-col :span="20"></el-col>
          <el-col :span="4">
            <vxe-button status="primary" @click="submitForm(ruleFormRef)">
              确认
            </vxe-button>
            <vxe-button content="默认颜色" @click="showEdit = false"
              >取消</vxe-button
            >
          </el-col>
        </el-row>
      </div>
    </vxe-modal>
  </div>
  <div>
    <vue3-html2pdf
      :show-layout="false"
      :float-layout="true"
      :enable-download="false"
      :preview-modal="true"
      :paginate-elements-by-height="2500"
      filename="hee hee"
      :pdf-quality="2"
      :manual-pagination="false"
      pdf-format="a4"
      pdf-orientation="landscape"
      pdf-content-width="800px"
      :html-to-pdf-options="htmlToPdfOptions"
      @progress="onProgress($event)"
      @hasStartedGeneration="hasStartedGeneration()"
      @hasGenerated="hasGenerated($event)"
      ref="html2Pdf"
    >
      <template v-slot:pdf-content>
        <vxe-table
          :loading="loading"
          show-overflow
          border="full"
          align="center"
          :row-config="{ isHover: true, height: 100 }"
          :column-config="{ resizable: true }"
          :data="tableData"
        >
          <vxe-column type="seq" title="序号" width="60"></vxe-column>
          <vxe-column field="category" title="新闻类型" width="80"></vxe-column>
          <vxe-column field="author" title="新闻作者" width="80"></vxe-column>
          <vxe-column field="title" title="新闻标题"></vxe-column>
          <vxe-column title="新闻图片" width="200">
            <template #default="{ row }">
              <img
                v-lazyImg="row.image"
                :data-src="row.image"
                class="image"
                style="width: 90px; height: 90px"
              />
            </template>
          </vxe-column>
        </vxe-table>
      </template>
    </vue3-html2pdf>
  </div>
</template>
<script lang="ts" setup>
import useList from "@/hooks/useList";
import { Plus, Loading } from "@element-plus/icons-vue";
import { onMounted, reactive, getCurrentInstance, ref } from "vue";
import { ElMessage } from "element-plus";
import NProgress from "nprogress"; // 引入nprogress插件
const { proxy } = getCurrentInstance();
const Progressbars = ref(false);
const generateReport = () => {
  proxy.$refs.html2Pdf.generatePdf();
};
const onProgress = (e) => {
  if (!Progressbars.value) {
    NProgress.start();
    Progressbars.value = true;
  } else {
    NProgress.done();
    Progressbars.value = false;
  }
};
const BASE_URL = import.meta.env.VITE_API_URL;
const htmlToPdfOptions = {
  margin: 0,
};
interface Form {
  id?: string;
  title?: string;
  author?: string;
  image?: string;
  createTime?: string;
  category?: string;
  content?: string;
}

// 表单重置初始化
const FormInitData = () => ({
  id: "",
  title: "",
  author: "",
  image: "",
  createTime: "",
  category: "",
  content: "",
});
// 图片上传成功时
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  uploadLoading.value = false;

  formData.image = response.data;
  // 单独对这个表单元素进行校验
  ruleFormRef.value?.validateField("image");
};
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  // 对文件格式和尺寸判断
  const isJPGOrPng = ["image/png", "image/jpeg"].indexOf(rawFile.type) !== -1;
  const isLt500K = rawFile.size / 1024 < 500;
  if (!isJPGOrPng) {
    ElMessage.error("上传图片只能是 JPG/PNG 格式！");
    return false;
  }
  if (!isLt500K) {
    ElMessage.error("上传图片大小不能超过500KB!");
    return false;
  }
  uploadLoading.value = true;
  return true;
};
// 表单校验
const rules = reactive<FormRules>({
  category: [{ required: true, message: "请输入新闻类型", trigger: "blur" }],
  title: [{ required: true, message: "请输入新闻标题", trigger: "blur" }],
  author: [{ required: true, message: "请输入新闻作者", trigger: "blur" }],
  image: [{ required: true, message: "上传新闻图片", trigger: "blur" }],
  content: [{ required: true, message: "请输入新闻详情", trigger: "blur" }],
});
const ColumnNames = [
  "id",
  "title",
  "author",
  "image",
  "content",
  "createTime",
  "category",
];
const {
  page,
  limit,
  total,
  loading,
  ruleFormRef,
  formData,
  showEdit,
  AddNus,
  tableData,
  submitForm,
  EmptyForm,
  insertEvent,
  recompose,
  deleteNewsList,
  Details,
  getNewsList,
  uploadLoading,
  storeAllImage,
  getAllImage,
  exportData,
  xTable,
  exportDataEvent,
} = useList<Form>({ url: "newsList", FormInitData, ColumnNames });
onMounted(async () => {
  await getNewsList(1, limit.value);
});
</script>
<script lang="ts">
import Vue3Html2pdf from "vue3-html2pdf";
export default {
  components: {
    Vue3Html2pdf,
  },
};
</script>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader :deep(.el-upload:hover) {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.demo-image__lazy {
  height: 400px;
  overflow-y: auto;
}
.demo-image__lazy .el-image {
  display: block;
  min-height: 200px;
  margin-bottom: 10px;
}
.demo-image__lazy .el-image:last-child {
  margin-bottom: 0;
}
</style>
